<template>
  <view>
    phoneInfo: {{ phoneInfo }}
    <button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
      获取用户手机号码
    </button>
  </view>
</template>

<script>
import { fetch } from '../../utils/fetch.js'
export default {
  data() {
    return {
      phoneNumber: '',
      regExp: '(\d{3})(\d{4})(\d{4})',
      // phone.replace(/(\d{3})(\d{4})(\d{4})/, "$1****$3")
    }
  },
  onLoad() {
    // 1. 获取token,
    const token = uni.getStorageSync('token')
    console.log('token:', token)
    if (!token) {
      wx.navigateTo({
        url: '/pages/center/center',
      })
    }
    // 2. you token 没有token
  },
  // 计算属性
  computed: {
    phoneInfo() {
      return this.phoneNumber.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3')
    },
  },
  methods: {
    async getPhoneNumber(e) {
      console.log('e:', e.detail.code)
      const access_token = uni.getStorageSync('access_token')
      if (access_token) {
        const res = await fetch({
          url: `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${access_token}`,
          method: 'POST',
          data: { code: e.detail.code },
        })
        console.log('res:', res.data.phone_info.phoneNumber)
        this.phoneNumber = res.data?.phone_info?.phoneNumber
      } else {
        uni.showToast({ title: 'access_token不存在' })
      }
    },
  },
}
</script>

<style lang="scss"></style>
